<template>
	<view class="home">
		<custom-navbar title='政策查询' :show-back="true" @back="handleBack" />

		<view class="content" :style="{ paddingTop: navBarHeight + 'px' }">
			<view class="search p0030">
				<view class="box fcc mb30">
					<up-search shape="square" :clearable="true" placeholder="请输入关键词搜索~" v-model="policy_title"
						:showAction="false"></up-search>
					<up-button type="primary" @click="getProductName()"
						style="width: 140rpx;height: 60rpx;background: #398DFB;border-radius: 10rpx 10rpx 10rpx 10rpx;"
						text="确定"></up-button>
				</view>
				<view class="fcsa f30c6">
					<view class="region-item" :class="{active: currentProvince.value}" @click="openProvincePicker">
						<text>{{currentProvince.label || '选择省份'}}</text>
						<image v-if="currentProvince.value" class="arrow-icon"
							src="/static/images/policy/arrow-down.svg" mode="aspectFit"></image>
						<image v-else class="arrow-icon" src="/static/images/policy/noarrow.svg" mode="aspectFit">
						</image>
					</view>
					<view class="region-item ml40" :class="{active: currentCity.value}" @click="openCityPicker"
						:style="{visibility: currentProvince.value ? 'visible' : 'hidden'}">
						<text>{{currentCity.label || '选择城市'}}</text>
						<image v-if="currentCity.value" class="arrow-icon" src="/static/images/policy/arrow-down.svg"
							mode="aspectFit"></image>
						<image v-else class="arrow-icon" src="/static/images/policy/noarrow.svg" mode="aspectFit">
						</image>
					</view>

					<view class="ml40 f30c6" @click="open">更多条件</view>
				</view>
			</view>

			<view class="p0030 notice">
				<view class="fc tabs">
					<view class="item fcc" :class="{active: day === ''}" @click="changeTab('')">全部结果</view>
					<view class="item fcc ml20" :class="{active: day === 'week'}" @click="changeTab('week')">最近7天内
					</view>
					<view class="item fcc ml20" :class="{active: day === 'month'}" @click="changeTab('month')">
						最近30天内</view>
				</view>

				<!-- 有数据时的显示 -->
				<view class="noticeList p30" v-if="ListData.length > 0">
					<view class="item" v-for="(item,index) in ListData" :key="index"
						@click="handleInquireDetails(item)">
						<view class="fcsb">
							<view class="fcols">
								<view class="f286c3 mb50">{{item.policy_title}}</view>
								<view class="f245c9">{{item.source}}</view>
								<view class="f245c9">{{item.create_time}}</view>
							</view>
							<view class="item-rigth fcolcc">
								<view class="mb8">结束倒计时</view>
								<view>{{item.remaining_time_text}}天</view>
							</view>
						</view>
						<up-line v-if="index < ListData.length - 1" margin='40rpx 0 40rpx 0'></up-line>
					</view>
				</view>

				<!-- 加载状态提示（移到列表外部） -->
				<view class="load-status">
					<view v-if="loading" class="loading-tip">
						<!-- <up-loading mode="circle"></up-loading> -->
						<text>加载中...</text>
					</view>
					<view v-if="noMoreData && ListData.length > 0" class="no-more-tip">
						已经到底了~
					</view>
				</view>
				<!-- 无数据时的显示 -->
				<view class="empty-state" v-if="!loading && ListData.length === 0">
					<!-- <image src="/static/images/policy/empty-search.png" mode="aspectFit"></image> -->
					<view class="empty-text">暂无搜索结果</view>
					<view class="empty-tip">换个关键词试试吧~</view>
				</view>
			</view>
		</view>

		<!-- 省份选择器 -->
		<up-picker :show="showProvincePicker" :columns="[provinceOptions]" keyName="label" @confirm="confirmProvince"
			@cancel="closeProvincePicker"></up-picker>

		<!-- 城市选择器 -->
		<up-picker :show="showCityPicker" :columns="[cityOptions]" keyName="label" @confirm="confirmCity"
			@cancel="closeCityPicker" :immediateChange="true"></up-picker>

		<!-- 区县选择器 -->
		<up-picker :show="showDistrictPicker" :columns="[districtOptions]" keyName="label" @confirm="confirmDistrict"
			@cancel="closeDistrictPicker" :immediateChange="true"></up-picker>

		<!-- 更多条件弹出框 -->
		<up-popup :show="show" :round="10" mode="right" bgColor="#F9FAFB" :custom-style="{
    width: '80%',
    position: 'fixed',
    right: '0',
    top: '0',
    bottom: '0',
	padding:'40rpx 0',   
  }" :safeAreaInsetTop="true" @close="close" @open="open">
			<view class="more p0030">
				<view class="tilte fc mb30">更多条件</view>
				<view class="category-list">
					<view class="category-item" v-for="(category, index) in categories" :key="index"
						@click="toggleCategory(index)">
						<view class="category-header fcsb">
							<view class="f306c3">{{category.name}}</view>
							<image class="wh32"
								:src="category.expanded ? '/static/images/policy/展开.svg' : '/static/images/policy/展开.svg'">
							</image>
						</view>
						<view class="category-options" v-if="category.expanded">
							<view class="option-item" v-for="(option, optIndex) in category.options" :key="optIndex"
								:class="{selected: option.selected}" @click.stop="selectOption(index, optIndex)">
								{{option.name}}
							</view>
						</view>
					</view>
				</view>

				<view class="action-buttons">
					<view>
						<up-button type="default"
							style="color: #398DFB;width: 243rpx;height: 80rpx;background: rgba(57,141,251,0.1);border-radius: 10rpx 10rpx 10rpx 10rpx;"
							text="重置" @click="resetFilters"></up-button>
					</view>
					<view>
						<up-button type="primary"
							style="width: 243rpx;height: 80rpx;border-radius: 10rpx 10rpx 10rpx 10rpx;" text="确定"
							@click="applyFilters"></up-button>
					</view>
				</view>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import CustomNavbar from '@/components/custom-navbar.vue'
	import {
		ref,
		onMounted
	} from 'vue';
	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'
	import {
		MatchingRuleLists,
		MatchingRulePolicy_matching
	} from '@/api/policy'
	import {
		getAddressSelect
	} from '@/api/user'

	const systemInfo = uni.getSystemInfoSync()
	const navBarHeight = systemInfo.statusBarHeight + 44

	// 搜索相关
	const searchKey = ref('')
	const policy_title = ref('')
	const day = ref('')

	// 地区相关
	const activeProvince = ref('天津')
	const activeCity = ref('静海区')
	const activeDistrict = ref('')

	const currentProvince = ref({})
	const currentCity = ref({})
	const currentDistrict = ref({})

	// 列表数据
	const ListData = ref([])

	// 地区选择器
	const showProvincePicker = ref(false)
	const showCityPicker = ref(false)
	const showDistrictPicker = ref(false)

	const provinceOptions = ref([])
	const cityOptions = ref([])
	const districtOptions = ref([])
	// 分页相关
	const page = ref(1) // 当前页码
	const limit = ref(10) // 每页条数
	const total = ref(0) // 数据总量
	const loading = ref(false) // 加载状态
	const noMoreData = ref(false) // 是否无更多数据
	// 更多条件
	const show = ref(false)
	const categories = ref([])
	const selectedOptions = ref([]) // 存储选中的rule_id
	// 获取筛选条件数据
	const getFilterConditions = async () => {
		try {
			const res = await MatchingRulePolicy_matching()
			if (res.code === 200) {
				categories.value = res.data.map(item => ({
					name: item.rule_name,
					rule_id: item.rule_id,
					expanded: false,
					options: item.children.map(child => ({
						name: child.rule_name,
						rule_id: child.rule_id,
						selected: false
					}))
				}))
			}
		} catch (error) {
			console.error('获取筛选条件失败:', error)
		}
	}
	// 修改获取列表方法
	const getMatchingRuleLists = async (isLoadMore = false) => {
		if (loading.value) return
		loading.value = true

		try {
			const params = {
				lang_code: 'zh',
				day: day.value,
				page: page.value,
				limit: limit.value,
				...(currentProvince.value?.value && {
					province_id: currentProvince.value.value
				}),
				...(currentCity.value?.value && {
					city_id: currentCity.value.value
				}),
				selectOption: selectedOptions.value.join(','),
				policy_title: policy_title.value
			}
			const Res = await MatchingRuleLists(params)

			if (Res.code === 200) {
				total.value = Res.data.total // 记录总数

				// 如果是加载更多，则追加数据
				if (isLoadMore) {
					ListData.value = [...ListData.value, ...(Res.data.data || [])]
				} else {
					// 否则替换数据
					ListData.value = Res.data.data || []
				}

				// 判断是否还有更多数据
				noMoreData.value = ListData.value.length >= total.value
			}
		} finally {
			loading.value = false
			uni.stopPullDownRefresh() // 停止下拉刷新动画
		}
	}
	// 加载更多数据
	const loadMore = () => {
		if (noMoreData.value || loading.value) return
		page.value += 1 // 页码+1
		getMatchingRuleLists(true) // 传true表示是加载更多
	}

	// 重置分页并刷新数据（用于搜索/筛选条件变化时）
	const refreshData = () => {
		page.value = 1 // 重置页码
		noMoreData.value = false // 重置数据状态
		getMatchingRuleLists() // 重新加载
	}
	// 获取地区数据
	const getRegionData = async (level, parent_code = '') => {
		try {
			const res = await getAddressSelect(level, parent_code)
			if (res.code === 200) {
				return res.data.map(item => ({
					label: item.label,
					value: item.value.toString(),
					level: item.level,
					parent_code: item.parent_code.toString()
				}))
			}
			return []
		} catch (error) {
			console.error('获取地区数据失败:', error)
			uni.showToast({
				title: '获取地区数据失败',
				icon: 'none'
			})
			return []
		}
	}

	// 初始化地区数据
	const initRegionData = async () => {
		// 获取省份数据
		const provinces = await getRegionData(1)
		provinceOptions.value = provinces

		// 默认不选择任何省份（全国）
		currentProvince.value = {}
		currentCity.value = {}
		currentDistrict.value = {}
		activeProvince.value = '选择省份'
		activeCity.value = '选择城市'
	}

	// 搜索
	const getProductName = () => {
		refreshData() // 改为调用refreshData
	}

	// 切换标签
	const changeTab = (tab) => {
		day.value = tab
		refreshData() // 改为调用refreshData
	}

	// 地区选择
	const openProvincePicker = async () => {
		if (provinceOptions.value.length === 0) {
			await initRegionData()
		}
		showProvincePicker.value = true
	}

	const openCityPicker = async () => {
		if (!currentProvince.value.value) return
		if (cityOptions.value.length === 0) {
			const cities = await getRegionData(2, currentProvince.value.value)
			cityOptions.value = cities
		}
		showCityPicker.value = true
	}

	const openDistrictPicker = async () => {
		if (!currentCity.value.value) return
		if (districtOptions.value.length === 0) {
			const districts = await getRegionData(3, currentCity.value.value)
			districtOptions.value = districts
		}
		showDistrictPicker.value = true
	}

	const closeProvincePicker = () => {
		showProvincePicker.value = false
	}

	const closeCityPicker = () => {
		showCityPicker.value = false
	}

	const closeDistrictPicker = () => {
		showDistrictPicker.value = false
	}

	// 确认省份选择
	const confirmProvince = async (e) => {
		const selected = e.value[0]
		currentProvince.value = {
			label: selected.label,
			value: selected.value
		}
		activeProvince.value = selected.label

		// 重置城市和区县
		currentCity.value = {}
		activeCity.value = '选择城市'
		cityOptions.value = []
		districtOptions.value = []

		closeProvincePicker()
		refreshData() // 替换getMatchingRuleLists()
	}
	// 确认城市选择
	const confirmCity = async (e) => {
		const selected = e.value[0]
		currentCity.value = {
			label: selected.label,
			value: selected.value
		}
		activeCity.value = selected.label

		// 重置区县
		currentDistrict.value = {}
		districtOptions.value = []

		closeCityPicker()
		refreshData() // 替换getMatchingRuleLists()
	}
	// 确认区县选择
	const confirmDistrict = (e) => {
		const selected = e.value[0]
		currentDistrict.value = {
			label: selected.label,
			value: selected.value // 确保保存value值
		}
		activeDistrict.value = selected.label
		closeDistrictPicker()
		refreshData() // 替换getMatchingRuleLists()
	}

	// 更多条件
	const open = () => {
		show.value = true
	}

	const close = () => {
		show.value = false
	}

	const toggleCategory = (index) => {
		categories.value[index].expanded = !categories.value[index].expanded
	}

	// 修改选项选择方法
	const selectOption = (categoryIndex, optionIndex) => {
		const option = categories.value[categoryIndex].options[optionIndex]
		option.selected = !option.selected

		// 更新选中项
		if (option.selected) {
			selectedOptions.value.push(option.rule_id)
		} else {
			selectedOptions.value = selectedOptions.value.filter(id => id !== option.rule_id)
		}
	}

	// 修改重置方法
	const resetFilters = () => {
		categories.value.forEach(category => {
			category.options.forEach(option => {
				option.selected = false
			})
		})
		selectedOptions.value = []
	}

	const applyFilters = () => {
		close()
		getMatchingRuleLists()
	}

	const handleBack = () => {
		uni.switchTab({
			url: '/pages/index/index'
		});
	};
	const handleInquireDetails = (item) => {
		uni.navigateTo({
			url: `/pages/policy/inquireDetails?matching_id=${item.matching_id}`
		})
	}
	onMounted(async () => {
		await initRegionData()
		await getFilterConditions()
		getMatchingRuleLists()
	})
	// 上拉加载更多（自动触发）
	onReachBottom(() => {
		loadMore()
	})

	// 下拉刷新（自动触发）
	onPullDownRefresh(() => {
		refreshData()
	})
</script>

<style lang="scss" scoped>
	.home {
		width: 100%;
		min-height: 100vh;
		overflow: hidden;
		background-color: #f7f7f7;

		.content {
			padding-top: var(--status-bar-height);
			padding-top: calc(var(--status-bar-height) + 70rpx);
			height: 100%;
			display: flex;
			flex-direction: column;

			.search {
				width: 100%;
				background: #FFFFFF;
				padding: 16rpx 30rpx 0 30rpx;
				box-sizing: border-box;

				.box {
					width: 100%;
					height: 90rpx;
					background: #F3F3F3;
					border-radius: 10rpx;
				}

				.region-item {
					display: flex;
					align-items: center;
					padding: 8rpx 16rpx;
					border-radius: 8rpx;
					min-width: 120rpx;

					&.active {
						color: #398DFB;
						font-weight: bold;
					}

					.arrow-icon {
						width: 24rpx;
						height: 24rpx;
						margin-left: 8rpx;
					}
				}

				.more-condition {
					color: #398DFB;
				}
			}

			.notice {
				flex: 1;

				.tabs {
					padding: 24rpx 0;

					.item {
						width: 184rpx;
						height: 66rpx;
						background: #FFFFFF;
						border-radius: 10rpx;

						&.active {
							background: #398DFB;
							color: #FFFFFF;
						}
					}
				}

				.noticeList {
					background: #FFFFFF;
					border-radius: 20rpx;

					.load-status {
						background: #FFFFFF;
						padding: 20rpx 0;
						border-radius: 0 0 20rpx 20rpx;

						.loading-tip,
						.no-more-tip {
							display: flex;
							justify-content: center;
							align-items: center;
							color: #999;
							font-size: 28rpx;

							text {
								margin-left: 16rpx;
							}
						}

						.no-more-tip {
							color: #ccc;
						}
					}

					.item {
						.item-rigth {
							width: 168rpx;
							height: 168rpx;
							font-family: PingFang SC, PingFang SC;
							font-weight: bold;
							font-size: 30rpx;
							color: #FFFFFF;
							text-align: center;
							flex-shrink: 0;
							/* 禁止收缩 */
							background: linear-gradient(90deg, #398DFB 0%, #61DBFF 100%);
							border-radius: 16rpx;
						}
					}
				}

				.empty-state {
					display: flex;
					flex-direction: column;
					align-items: center;
					justify-content: center;
					padding: 100rpx 0;
					background: #FFFFFF;
					border-radius: 20rpx;

					image {
						width: 300rpx;
						height: 300rpx;
						margin-bottom: 40rpx;
					}

					.empty-text {
						font-size: 32rpx;
						color: #666;
						margin-bottom: 20rpx;
					}

					.empty-tip {
						font-size: 28rpx;
						color: #999;
					}
				}
			}
		}

		.more {
			height: 100%;
			display: flex;
			flex-direction: column;

			.tilte {
				height: 80rpx;
				font-size: 36rpx;
				font-weight: bold;
				color: #333;
			}

			.category-list {
				flex: 1;
				overflow-y: auto;

				.category-item {
					margin-bottom: 30rpx;

					.category-header {
						padding: 20rpx 0;
						border-bottom: 1rpx solid #eee;

						image {
							width: 30rpx;
							height: 30rpx;
						}
					}

					.category-options {
						padding: 20rpx 0;
						display: flex;
						flex-wrap: wrap;

						.option-item {
							padding: 12rpx 38rpx;
							display: flex;
							justify-content: center;
							align-items: center;
							margin: 10rpx 20rpx 10rpx 0;
							border-radius: 8rpx;
							background: #FFFFFF;
							border-radius: 6rpx 6rpx 6rpx 6rpx;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 26rpx;
							color: #666666;
							text-align: left;
							font-style: normal;
							text-transform: none;

							&.selected {
								background: #398DFB;
								border-radius: 8rpx 8rpx 8rpx 8rpx;
								font-family: PingFang SC, PingFang SC;
								font-weight: 500;
								font-size: 26rpx;
								color: #FFFFFF;
								text-align: left;
								font-style: normal;
								text-transform: none;
							}
						}
					}
				}
			}

			.action-buttons {
				display: flex;
				justify-content: space-between;
				padding: 30rpx 0;

				.up-button {
					width: 243rpx;
				}
			}
		}
	}
</style>